package org.ftz.JudgeOnline.Java;
import org.ftz.JudgeOnline.Java.Answer;
import java.io.*;
public class ExecUtil {
    private ExecUtil(){}
    public static Answer run(String cmd, Boolean stdoutB, Boolean stderrB){
        Answer answer=new Answer();
        try {
            Process process=Runtime.getRuntime().exec(cmd); //1.通过Runtime类得到实例，执行exec方法
            String line="",re="",stdout=""; //2.获取到标准输出，并写入到指定文件中
            if(stdoutB){
                InputStream inputStream = process.getInputStream();
                InputStreamReader gbk = new InputStreamReader(inputStream, "GBK");
                BufferedReader stdoutFrom=new BufferedReader(gbk);
                while((line=stdoutFrom.readLine())!=null)
                    stdout+=line+"\n";
                stdoutFrom.close();;
            }
            if(stderrB){
                InputStream errorStream = process.getErrorStream();
                InputStreamReader gbk = new InputStreamReader(errorStream, "GBK");
                BufferedReader stdoutFrom=new BufferedReader(gbk);
                while((line=stdoutFrom.readLine())!=null) {
                    re+=line+"\n";
                }
                stdoutFrom.close();
            }
            int exitCode=process.waitFor(); //exec 执行过程是异步的,waitfor会阻塞主进程，直到子进程完毕
            answer.setError(exitCode);
            answer.setStderr(re);
            answer.setStdout(stdout);
            return answer;
        }catch (IOException |InterruptedException e){
            e.printStackTrace();
        }
        answer.setError(2);
        return answer;
    }
}
